package com.yx.modules.api.controller;

import com.yx.common.annotation.Log;
import com.yx.common.utils.PageUtils;
import com.yx.common.utils.Query;
import com.yx.common.utils.R;
import com.yx.modules.api.Dto.SectionDto;
import com.yx.modules.api.annotation.AuthIgnore;
import com.yx.modules.api.annotation.LoginUser;
import com.yx.modules.api.entity.TbToken;
import com.yx.modules.api.entity.TbUser;
import com.yx.modules.api.entity.TbVolume;
import com.yx.modules.api.service.TbTokenService;
import com.yx.modules.api.service.TbUserService;
import com.yx.modules.api.service.TbVolumeService;
import com.yx.pc.api.Dto.TbSectionDto;
import com.yx.system.dao.TdOrderMapper;
import com.yx.system.entity.*;
import com.yx.system.service.TdBookService;
import com.yx.system.service.TdCollectionService;
import com.yx.system.service.TdOrderService;
import com.yx.system.service.TdSectionService;
import com.yx.system.service.impl.TdTextServiceImpl;
import com.yx.utils.PayStatus;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 章节控制器
 */
@RestController
@RequestMapping("/api/section")
public class TdSectionController {

    @Autowired
    private TdSectionService tdSectionService;
    @Autowired
    private TdTextServiceImpl tdTextService;
    @Autowired
    private TdOrderService tdOrderService;
    @Autowired
    private TbTokenService tbTokenService;
    @Autowired
    private TbUserService tbUserService;
    @Autowired
    private TdBookService tdBookService;
    @Autowired
    private TbVolumeService tbVolumeService;
    @Autowired
    private TdCollectionService tdCollectionService;
    /**
     * 按ID查询
     *
     * @return
     */
    @AuthIgnore
    @PostMapping("findById")
    public R findById(String token, int id) {
        TbToken tbToken = tbTokenService.queryByToken(token);
        TbUser tbUser = null;
        if (tbToken != null) {
            tbUser = tbUserService.foundById(tbToken.getUserId());
        }
        Map<String, Object> map = new HashMap<>();
        TdSection tdSection = tdSectionService.selectByPrimaryKey(id);
        //判断是否购买
        map.put("section", tdSection);
        if (tdSection.getTotalfee() > 0) {
            if (tbUser!=null) {
                Map<String, Object> par = new HashMap<>();
                par.put("uuid", tbUser.getUuid());
                par.put("sectionid", tdSection.getId());
                par.put("orderStatus", PayStatus.success.getName());
                List<TdOrder> tdOrderList = tdOrderService.queryList(par);
                if (tdOrderList.size() > 0) {
                    map.put("context", tdTextService.findByInfo(tdSection.getUuid()));
                    //根据用户uuid和图书id去查询收藏
                    TdCollection tdCollection = tdCollectionService.findByUserAndBook(tbUser.getUuid(),tdSection.getBookid());
                    //查询所有章节id集合
                    List<Integer> ids = tdSectionService.findIdList(tdSection.getBookid());
                    //初始化章节所占下标
                    Double index = Double.valueOf(0);
                    //查询当前章节id所占的下标
                    for (int i=0;i<ids.size();i++){
                        if (tdSection.getId()==ids.get(i)){
                            index = Double.valueOf(i+1);
                        }
                    }
                    //如果不为空就更新最新阅读到的章节和阅读进度
                    if (tdCollection!=null){
                        tdCollection.setSectionid(tdSection.getId());
                        tdCollection.setSectionname(tdSection.getSectionname());
                        if (index!=0){
                            //更新阅读进度
                            tdCollection.setReadRation(Double.valueOf(index/ids.size()));
                        }
                        tdCollectionService.updateByPrimaryKey(tdCollection);
                    }
                }
            }
        } else {
            map.put("context", tdTextService.findByInfo(tdSection.getUuid()));
            if (tbUser!=null){
                //根据用户uuid和图书id去查询收藏
                TdCollection tdCollection = tdCollectionService.findByUserAndBook(tbUser.getUuid(),tdSection.getBookid());
                //查询所有章节id集合
                List<Integer> ids = tdSectionService.findIdList(tdSection.getBookid());
                //初始化章节所占下标
                Double index = Double.valueOf(0);
                //查询当前章节id所占的下标
                for (int i=0;i<ids.size();i++){
                    if (tdSection.getId()==ids.get(i)){
                        index = Double.valueOf(i+1);
                    }
                }
                //如果不为空就更新最新阅读到的章节和阅读进度
                if (tdCollection!=null){
                    tdCollection.setSectionid(tdSection.getId());
                    tdCollection.setSectionname(tdSection.getSectionname());
                    if (index!=0){
                        //更新阅读进度
                        tdCollection.setReadRation(Double.valueOf(index/ids.size()));
                    }
                    tdCollectionService.updateByPrimaryKey(tdCollection);
                }
            }
        }
        return R.ok().put("data", map);
    }


    /**
     * 查询所有
     *
     * @param map
     * @return
     */
    @AuthIgnore
    @PostMapping("findAllByCondition")
    public R findAllByCondition(@RequestParam Map<String, Object> map) {
        Query query = new Query(map);
        List<TdSection> tdSectionList = tdSectionService.queryList(query);
        int total = tdSectionService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(tdSectionList, total, query.getLimit(), query.getPage());
        return R.ok().put("data", pageUtil);
    }


    /*
    * 查询图书下的卷，及其章节
    *
    */
    @AuthIgnore
    @RequestMapping("findVolumeAndSection")
    public R findVolumeAndSection(Integer bookId){
        //先找到图书
        TdBook tdBook = tdBookService.selectByPrimaryKey(bookId);
        //初始化最终数据传输对象
        SectionDto sectionDto = new SectionDto();
        //判断图书
        if (tdBook==null){
            return R.error("查无此书");
        }
        //初始化数据传输对象集合
        List<TbSectionDto> tbSectionDtos = new ArrayList<>();
        //查询所有的卷
        List<TbVolume> tbVolumes = tbVolumeService.findByBookId(bookId);
        if (tbVolumes.size()!=0){
            //根据卷查询卷下的所有章节
            for (TbVolume tbVolume:tbVolumes){
                //初始化数据传输对象
                TbSectionDto tbSectionDto = new TbSectionDto();
                //根据卷去查询章节集合
                List<TdSection> tdSections = tdSectionService.findByVolumeId(tbVolume.getId());
                if (tdSections.size()!=0){
                    tbSectionDto.setTdSections(tdSections);
                }
                tbSectionDto.setTbVolume(tbVolume);
                tbSectionDtos.add(tbSectionDto);
            }
        }
        //查询图书的所有章节id，升序排列
        List<Integer> sectionIds = tdSectionService.findSectionIds(bookId);
        //注入dto
        sectionDto.setSectionIds(sectionIds);
        sectionDto.setTbSectionDtos(tbSectionDtos);

        return R.ok().put("data",sectionDto);
    }

}
